package com.ivan.stu.notetool.network.intercepter;

import android.util.Log;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

import static com.alibaba.fastjson.util.IOUtils.UTF8;

/**
 * Author: gongwq on 2017/12/20 002055.
 * Email: gwq_0111@163.com
 * Descriptions: 网络拦截器
 */

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //chain包含了request和response
        Request request = chain.request();
        long requestTime = System.nanoTime();
        HttpUrl url = request.url();
        RequestBody requestBody = request.body();
        Connection requestConnection = chain.connection();
        Headers requestHeaders = request.headers();
        String method = request.method();
        String body = null;

        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            body = buffer.readString(charset);
        }

        //打印发送信息
        String requestInfo = String.format("发送请求\nmethod：%s\nurl：%s\nheaders: %s\nbody：%s",
                request.method(), request.url(), request.headers(), body);
        Log.e("拦截请求---->", requestInfo);

      //  long responseTime = System.nanoTime();
        Response response = chain.proceed(chain.request());
        ResponseBody responseBody = response.peekBody(response.body().contentLength());
        HttpUrl responseUrl = response.request().url();
        Headers responseHeaders = response.headers();
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - requestTime);
        String responseInfo = String.format("收到响应 %s  %s  %sms\n请求url：%s\n请求body：%s\n响应body：%s",
                response.code(), response.message(), tookMs, response.request().url(), body, responseBody.string());
        Log.e("拦截返回---->", responseInfo);
        return response;
    }
}
